<template>
	<!-- 周期 -->
	<view class="period-container list-bg">
		<view class="period-container-box" v-if="isShow">
			<!-- 头部 -->
			<view class="menu-box dis-between padd-auto">
				<view class="menu-image">
					<image @click="leftShow = true" class="image" src="../../static/images/ui/menu.png"
						mode="heightFix"></image>
					<text class="white-text bold">{{legal_name + '/' + currency_name}}</text>
				</view>
				<image @click="horizontalScreen" class="image" src="../../static/images/ui/screen.png" mode="heightFix">
				</image>
			</view>
			<!-- 金额 -->
			<view class="price-box dis-between padd-auto">
				<view class="left-box">
					<text class="bold fall">{{last_price}}</text>
					<view>
						<text class="white-text">≈￥{{last_price * Number(ExRAte) | xiaoshudian}}</text>
						<text :class="Number(change) <= 0?'fall': 'rise'">{{change}}%</text>
					</view>
				</view>
				<view class="right-box dis-between">
					<view class="dis-between">
						<text>H</text>
						<text class="white-text">{{lever_hight}}</text>
					</view>
					<view class="dis-between">
						<text>L</text>
						<text class="white-text">{{lever_low}}</text>
					</view>
					<view class="dis-between">
						<text>24H</text>
						<text class="white-text">{{lever_24hight}}</text>
					</view>
				</view>
			</view>
			<!-- k线图的tab -->
			<view class="line-empty"></view>
			<tabs :list="kLineList" :fontSize="24" padding="30rpx" @click="kLineClick"></tabs>
			<!-- k线图 -->
			<view ref="divklinechart" class="k-line-container view-bg">
				<!-- <pei-chart :height="460" ref='ht0' :dataAs="chartData" canvasId="ht0" /> -->
				<!--  #ifdef  H5 -->
				<div>
					<div class='kline' id="kline" ref='kline'></div>
				</div>
				<!--  #endif -->

				<!--  #ifndef  H5 -->
				<view>
					<canvas id="kline2" canvas-id='kline2' class='kline2'
						v-bind:style="{width: ChartWidth+'px', height: ChartHeight+'px'}" @touchstart="KLineTouchStart"
						@touchmove='KLineTouchMove' @touchend='KLineTouchEnd'></canvas>
				</view>
				<!--  #endif -->
			</view>
			<!-- k线图数值 -->
			<view class="k-line-value dis-between padd-auto white-text">
				<view>
					<text>{{i18n.point.usable + "："}}</text>
					<text>{{Number(user_price)}}</text>
				</view>
				<view>
					<text>{{i18n.point.freeze + "："}}</text>
					<text>{{Number(userlock_price)}}</text>
				</view>
			</view>
			<!-- 间隔 -->
			<view class="empty view-bg"></view>
			<!-- 底部数据 -->
			<view class="data-container">
				<!-- 底部导航栏 -->
				<tabs :list="tabsList" :fontSize="32" @click="tabsClick"></tabs>
				<view class="data-title">
					<text>{{i18n.period.time}}</text>
					<text>{{i18n.period.direction}}</text>
					<text>{{i18n.period.profitPrice}}</text>
					<text>{{i18n.period.exitPrice}}</text>
					<text>{{i18n.period.profitCell}}</text>
				</view>
				<view class="data-list dis-between" v-for="(item, index) in dataList" :key="index">
					<text>{{item.create_time | formateCreateTime}}</text>
					<text :class="item.type === 2?'fall': 'rise'">{{item.type | direction(i18n.period)}}</text>
					<text>{{item.now_price | xiaoshudian}}</text>
					<text>{{transactionIndex !== 'intrade'?item.update_price :item.last_price | xiaoshudian}}</text>
					<text :class="Number(item.fact_profits) > 0? 'rise': 'fall'">{{ Number(item.fact_profits) > 0? i18n.period.profitText: i18n.period.loss }}</text>
				</view>
			</view>
		</view>
		<!-- 按钮 -->
		<view class="data-btn dis-between list-bg" v-if="isShow">
			<view class="btn rise" @click="dataBtnClick(1)">
				<text>{{i18n.period.buy}}</text>
			</view>
			<view class="btn fall" @click="dataBtnClick(2)">
				<text>{{i18n.period.sell}}</text>
			</view>
		</view>
		<!-- 关闭以后显示 -->
		<view class="period-empty" v-else>
			<text>{{!is_open_leagl? is_open_leaglremarks: is_open_grealzq? i18n.common.seniorAuth: i18n.common.primaryAuth}}</text>
		</view>
		<!-- 左边侧边栏 -->
		<u-popup v-model="leftShow" width="620">
			<view class="left-container container list-bg">
				<view class="left-top dis-between">
					<text class="white-text">{{i18n.period.periodTreaty}}</text>
					<image @click="leftShow = false" class="image" src="../../static/images/ui/menu.png"
						mode="heightFix"></image>
				</view>
				<view v-for="(item, index) in currencyShowList" :key="index" v-if="item.name === 'USDT'">
					<view class="dis-between left-list" v-for="(j, k) in item.quotation" :key="k"
						@click="leftShowViewBtn(item, j, true)">
						<view>
							<text class="white-text bold">{{item.name}}</text>
							<text>{{'/' + j.currency_name}}</text>
						</view>
						<text class="fall bold">{{j.now_price}}</text>
					</view>
				</view>
			</view>
		</u-popup>
		<!-- 底部侧边栏 -->
		<u-popup v-model="bottomShow" height="1100" mode="bottom">
			<view class="bottom-container list-bg">
				<view class="bottom-top dis-between">
					<text class="white-text">{{legal_name + '/' + currency_name}}</text>
					<view class="dis-between">
						<text class="fall">{{last_price}}</text>
						<text @click="bottomShow = false">{{i18n.common.cancel}}</text>
					</view>
				</view>
				<view class="container">
					<view class="bottom-time dis-between white-text">
						<text>{{currentTime}}</text>
					</view>
					<view class="dis-between">
						<text>{{i18n.period.assets}}</text>
						<text class="main-color bold">{{'USDT'}}</text>
					</view>
					<view class="dis-between">
						<text>{{i18n.period.usable}}</text>
						<text class="white-text bold">{{user_lever || 0}}</text>
					</view>
					<view class="dis-between">
						<text>{{i18n.period.quantity}}</text>
						<view class="btn">
							<input @blur="periodBlur" v-model="info.origin_price" type="number"
								:placeholder="i18n.period.enter" style="padding: 20rpx 30rpx;" />
						</view>
					</view>
					<view class="dis-between right">
						<view class="btn dis-between">
							<view class="min-btn" :class="pointIndex === index?'main-bg': ''"
								v-for="(item, index) in ratio" :key="index" @click="pointClick(index,item)">
								<text class="white-text">{{item.value + '%'}}</text>
							</view>
						</view>
					</view>
					<view class="dis-between">
						<text>{{i18n.period.transaction}}</text>
						<dropdown-box @click="transactionClick" :regionList="share" company="S"></dropdown-box>
					</view>
					<view class="dis-between expected">
						<view class="white-text">
							<text>{{i18n.period.expected + '：'}}</text>
							<text>{{reward + '%'}}</text>
						</view>
						<view class="white-text">
							<text>{{i18n.period.reward + '：'}}</text>
							<text>{{info.origin_price | price(reward)}}</text>
						</view>
					</view>
					<custom-submit :loading="loading" :title="popbtnTitle" @click="bottomClick"></custom-submit>
				</view>
			</view>
		</u-popup>
		<!-- 验证登录 -->
		<tips-popup ref="tips"></tips-popup>
		<custom-loading text="" mask="true" click="true" ref="loading"></custom-loading>
	</view>
</template>

<script>
	// #ifdef H5
	import HQChart from '../../js_sdk/jones-hqchart/umychart_uniapp_h5/umychart.uniapp.h5.js'
	// #endif

	// #ifndef H5
	import {
		JSCommon
	} from '../../js_sdk/jones-hqchart/umychart.uniapp/umychart.wechat.3.0.js'
	import {
		JSCommonHQStyle
	} from '../../js_sdk/jones-hqchart/umychart.uniapp/umychart.style.wechat.js'
	// #endif

	HQChart.JSConsole.Chart.Log = function() {} //不输出图形日志
	HQChart.JSConsole.Complier.Log = function() {} //不输出指标脚本执行日志

	var pako = require('pako');

	function DefaultData() {}

	DefaultData.GetKLineOption = function() {
		let data = {
			Type: '历史K线图',

			Windows: //窗口指标
				[{
						Index: "EMPTY",
						Modify: false,
						Change: false,
						TitleHeight: 0
					},
					// {Index:"VOL",Modify: false, Change: false}
				],

			IsClickShowCorssCursor: true, //手势点击出现十字光标
			IsCorssOnlyDrawKLine: true, //十字光标在K线中间
			CorssCursorTouchEnd: true, //手势离开屏幕十字光标自动隐藏
			IsAutoUpdate: false, //是自动更新数据(不自动更新由外部更新)
			IsApiPeriod: true, //使用Api计算周期

			Border: //边框
			{
				Left: 1,
				Right: 1, //右边间距
				Top: 0,
				Bottom: 0,
			},

			KLine: {
				Right: 1, //复权 0 不复权 1 前复权 2 后复权
				Period: 4, //周期: 0 日线 1 周线 2 月线 3 年线 
				PageSize: 30,
				RightSpaceCount: 3,
				IsShowTooltip: false
			},

			Frame: //子框架设置
				[{
						SplitCount: 3, //Y轴3等份
						IsShowLeftText: false, //左侧不显示刻度文字
						SplitType: 1,
						Height: 8, //高度比值
						Custom: [{
							Type: 0,
							Position: 'right'
						}] //最新价格刻度
					},

					{
						SplitCount: 2, //Y轴2等份
						IsShowLeftText: false, //左侧不显示刻度文字
						SplitType: 1,
						Height: 2
					},
				],
			KLineTitle: {
				IsShowName: false,
				IsShowSettingInfo: false
			},

			ExtendChart: [{
					Name: 'KLineTooltip'
				}, //开启手机端tooltip
			],

		};

		return data;
	}

	var g_KLine = {
		JSChart: null
	};

	import CustomSubmit from '@/components/CustomSubmit/index.vue'
	import DropdownBox from '@/components/DropdownBox/index.vue'
	import Tabs from '@/components/Tabs/index.vue'
	import TipsPopup from '@/components/TipsPopup/index.vue'
	import CustomLoading from '@/components/Loadidng/index.vue'
	import {
		mapGetters
	} from 'vuex'
	import {
		currencyNew_timeshar,
		leverPdsubmit,
		leverDeal,
		leverBatchzq_close
	} from '@/api/index.js'
	import {
		Toast,
		formateTime
	} from '@/utils/util.js'
	export default {
		components: {
			CustomSubmit,
			DropdownBox,
			Tabs,
			TipsPopup,
			CustomLoading
		},
		filters: {
			price(val, reward) {
				if (!val) return '';
				return Number(val) + Number(val * reward)
			},
			direction(val, language) {
				let name = '';
				switch (val) {
					case 1:
						name = language.buy
						break;
					case 2:
						name = language.sell
						break;
				}
				return name;
			},
			formateCreateTime(val) {
				return formateTime(val, true);
			},
			xiaoshudian(val) {
				return Math.round((Number(val) * 100)) / 100
			},
			is_profit(val, language) {
				if (Number(val) > 0) return language.profitText;
				return language.loss;
			},
			is_class(val) {
				if (Number(val) > 0) return 'rise';
				return 'fall';
			}
		},
		data() {
			return {
				dataListObj: {},
				dataList: [],
				leftShow: false,
				leftList: [{
						title: 'BTC',
						price: '31466.06'
					},
					{
						title: 'BTC',
						price: '31466.06'
					},
					{
						title: 'BTC',
						price: '31466.06'
					},
					{
						title: 'BTC',
						price: '31466.06'
					},
				],
				bottomShow: false,
				pointIndex: null,
				popbtnTitle: '',
				info: {},
				loading: false,
				ratio: [],
				share: [],
				legal_name: 'BTC',
				currency_name: 'USDT',
				reward: 0,
				period: '1min',
				transactionIndex: 'profit',
				isRequest: false,
				ExRAte: 0,
				last_price: 0.013,
				lever_24hight: 0.022,
				lever_hight: 0.012,
				lever_low: 0.047,
				legalObj: {},
				currencyObj: {},
				currentTime: 0,
				user_lever: 0,
				change: 0,
				time: null,
				user_price: null,
				userlock_price: null,

				Symbol: 'btcusdt.BIT',
				OriginalSymbol: 'btcusdt',
				ChartWidth: 0,
				ChartHeight: 0,
				KLine: {
					Option: DefaultData.GetKLineOption(),
				},

				WSUrl: 'wss://api.huobiasia.vip/ws',
				SocketOpen: false,
				LastSubString: null, //最后一个订阅的数据
			}
		},
		computed: {
			...mapGetters(['token', 'currencyShowList', 'is_open_leagl', 'is_open_leaglremarks', 'is_open_realzq', 'is_open_grealzq', 'review_status']),
			tabsList() {
				return [{
					title: this.$t('message').period.profit,
					value: 'profit'
				}, {
					title: this.$t('message').period.positions,
					value: 'intrade'
				}, {
					title: this.$t('message').period.ifset,
					value: 'deal'
				}]
			},
			kLineList() {
				return [{
						title: this.$t('message').common.first_m,
						value: 4
					},
					{
						title: this.$t('message').common.five_m,
						value: 5
					},
					{
						title: this.$t('message').common.fifteen_m,
						value: 6
					},
					{
						title: this.$t('message').common.thirty_m,
						value: 7
					},
					{
						title: this.$t('message').common.first_d,
						value: 0
					},
					{
						title: this.$t('message').common.first_w,
						value: 1
					},
					{
						title: this.$t('message').common.first_mon,
						value: 2
					},
					{
						title: this.$t('message').common.first_y,
						value: 3
					},
				]
			},
			i18n() {
				return this.$t('message');
			},
			isShow() {
				if (!this.is_open_leagl || (this.is_open_realzq && this.review_status === 0) || (this.is_open_grealzq && this.review_status !== 4)) return false;
				return true;
			}
		},
		onReady() {
			if (!this.isShow) {
				// this.$refs.loading.close();
				return;
			}
			this.$refs.loading.open();

			this.$nextTick(() => {
				// #ifndef H5
				this.OnSize();
				this.CreateKLineChart();
				// #endif
			});
			let id = uni.getStorageSync('periodId');
			if (!id) return;
			this.customDefault(id);
			uni.setStorageSync('periodId', "");
		},
		onShow() {
			if (!this.isShow) return;
			let _this = this;
			uni.getSystemInfo({
				success: (res) => {
					_this.$nextTick(() => {
						_this.OnSize();
						_this.CreateKLineChart();
					})
				}
			});
		},
		onLoad() {
			// 导航栏多语言
			uni.setNavigationBarTitle({
				title: this.i18n.tabBar.period
			});
		},

		onHide() {
			if (!this.isShow) return;
			if (this.SocketOpen) {
				uni.closeSocket();
				this.SocketOpen = false;
			}

			this.ClearChart();
		},

		onUnload() {
			if (!this.isShow) return;
			if (this.SocketOpen) {
				uni.closeSocket();
				this.SocketOpen = false;
			}

			this.ClearChart();
		},

		async activated() {
			if (!this.isShow) return;
			if (!this.token) return this.$refs.tips.open('confirm', this.i18n.common.loginTips);
			await this.customDefault()
			this.isRequest = true;
			this.getKline()
		},
		deactivated() {
			if (!this.isShow) return;
			this.isRequest = false;
			clearInterval(this.time)
			this.time = null;
		},
		async mounted() {
			if (!this.isShow) return;
			if (!this.token) {
				this.$refs.loading.close();
				this.$refs.tips.open('confirm', this.i18n.common.loginTips);
				return;
			}

			if (this.currencyShowList.length) {
				await this.customDefault();
				this.isRequest = true;
				this.getKline();
				return;
			}

			this.$store.dispatch('currency/getCurrencyList').then(() => {
				this.customDefault();
				this.isRequest = true;
				this.getKline();
			})
		},
		methods: {
			// 底部百分比切换
			pointClick(idx, item) {
				if (this.pointIndex === idx) return;
				this.pointIndex = idx;
				if (!this.user_lever) return;
				this.info.origin_price = this.user_lever * ((item.value) / 100)
			},
			// k线图
			async K_line_load(time) {
				this.chartData.categories = [];
				this.chartData.series[0].data = [];
				let {
					error,
					res
				} = await currencyNew_timeshar({
					period: this.period,
					from: Date.parse(new Date()) / 1000 - time,
					to: Date.parse(new Date()) / 1000,
					symbol: this.currency_name + '/' + this.legal_name
				});
				if (error) return;

				if (!res.length) return;
				let arry = []
				for (let i in res) {
					this.chartData.categories.push('');
					let obj = [
						Number(res[i].open),
						Number(res[i].close),
						Number(res[i].low),
						Number(res[i].high),
					]
					arry.push(obj);
				}
				this.chartData.series[0].data = arry;
				this.$refs.loading.close();
				this.$refs.ht0.uchartsUpdata(this.chartData)
			},
			// 底部导航栏切换
			tabsClick(val) {
				this.transactionIndex = val;
				this.dataList = this.dataListObj[val];
			},
			// 底部弹窗提交按钮
			async bottomClick() {
				if (!this.info.origin_price) return Toast(this.i18n.period.enter);
				if (Number(this.info.origin_price) > Number(this.user_lever)) return Toast(this.i18n.period.noOver);
				this.info.token = this.token;
				this.loading = true;
				this.info.last_price = this.last_price;
				this.info.profits = Number(this.info.origin_price) + Number(this.info.origin_price * this.reward)
				let {
					error,
					res
				} = await leverPdsubmit(this.info);
				if (error) return this.loading = false;;
				await Toast(this.i18n.period.success);
				this.loading = false;
				this.bottomShow = false;
				this.$store.dispatch('user/getInfo');
			},
			// 选择交易期间
			transactionClick(val) {
				this.info.share = val.value;
				this.reward = val.predict;

			},
			// leverBatchzq_close
			async getLeverBatchzq_close() {
				let {
					error,
					res
				} = await leverBatchzq_close({
					token: this.token
				});
				if (error) return;
			},
			// 周期详情
			async leftShowViewBtn(first, last, close) {
				if (first !== undefined) {
					this.legalObj = first;
				}
				if (last !== undefined) {
					this.currencyObj = last
				}
				let {
					error,
					res
				} = await leverDeal({
					legal_id: this.legalObj.id,
					currency_id: this.currencyObj.currency_id,
					token: this.token
				});
				if (error) return;
				this.info.legal_id = this.legalObj.id;
				this.info.currency_id = this.currencyObj.currency_id;
				this.legal_name = this.legalObj.name;
				this.currency_name = this.currencyObj.currency_name;
				this.ratio = res.multiple.ratio;
				this.share = res.multiple.share;
				this.reward = this.share[0].predict;
				this.info.share = this.share[0].value;
				// 顶部数据 start
				this.ExRAte = res.ExRAte;
				// this.last_price = res.last_price;
				this.lever_24hight = res.lever_24hight;
				// this.lever_hight = res.lever_hight;
				// this.lever_low = res.lever_low;
				this.user_lever = res.user_price;
				this.change = res.change;	
				this.user_price = res.user_price;
				this.userlock_price = res.user_profits;
				this.change = res.change;
				// end
				this.dataListObj = res.lever_transaction;
				this.dataList = this.dataListObj[this.transactionIndex];
				this.$refs.loading.close();
				if (!close) return;
				this.leftShow = false;
			},
			// tabs切换请求K线
			kLineClick(val) {
				this.ChangePeriod(typeof(val) === 'object'? val.value:val);
			},
			// 循环请求k线
			getKline() {
				let _this = this;
				clearInterval(_this.time)
				_this.time = null;
				if (!_this.isRequest) return;
				_this.time = setInterval(() => {
					_this.getLeverBatchzq_close();
					_this.leftShowViewBtn(this.legalObj, this.currencyObj, false);
					_this.getKline();
				}, 1500)
			},
			// 输入金额失焦
			periodBlur() {
				this.pointIndex = null;
			},
			// 显示usdt下的币种
			customDefault(id) {
				for (let i in this.currencyShowList) {
					if (this.currencyShowList[i].name === 'USDT') {
						if (id) {
							for (let o in this.currencyShowList[i].quotation) {
								if (this.currencyShowList[i].quotation[o].currency_id === id) {
									this.leftShowViewBtn(this.currencyShowList[i], this.currencyShowList[i].quotation[o],
										false);
								}
							}
							break;
						}
						this.leftShowViewBtn(this.currencyShowList[i], this.currencyShowList[i].quotation[0], false);
					}
				}
			},

			dataBtnClick(type) {
				this.bottomShow = true;
				this.info.type = type;
				this.popbtnTitle = type === 1 ? this.i18n.period.buy : this.i18n.period.sell;
				this.currentTime = formateTime(new Date());
			},

			horizontalScreen() {
				uni.navigateTo({
					url: '/pages/period/horizontalScreen'
				})
			},
			//对外接口
			ChangePeriod(period) //周期切换
			{
				//var symbol=this.Symbol;
				// console.log(period)
				g_KLine.JSChart.ChangePeriod(period);
			},

			ChangeSymbol(symbol) //切换股票
			{
				if (this.OriginalSymbol == symbol) return;

				this.OriginalSymbol = symbol;
				this.Symbol = symbol + '.BIT';
				g_KLine.JSChart.ChangeSymbol(this.Symbol);
			},

			OnSize() {
				// #ifdef H5
				this.OnSize_h5();
				// #endif
			},

			OnSize_h5() {

				let divKLineChart = this.$refs.divklinechart.$el;
				this.ChartHeight = divKLineChart.offsetHeight;
				this.ChartWidth = divKLineChart.offsetWidth;

				let kline = this.$refs.kline;
				kline.style.width = this.ChartWidth + 'px';
				kline.style.height = this.ChartHeight + 'px';
				if (g_KLine.JSChart) g_KLine.JSChart.OnSize();
			},

			ClearChart() {
				if (g_KLine.JSChart) {
					g_KLine.JSChart.ChartDestory();
					g_KLine.JSChart = null;
				}

				// #ifdef H5
				var divKLine = document.getElementById('kline');
				while (divKLine.hasChildNodes()) {
					divKLine.removeChild(divKLine.lastChild);
				}
				// #endif
			},

			CreateKLineChart_h5() //创建K线图
			{
				if (g_KLine.JSChart) return;

				//黑色风格
				let blackStyle = HQChart.HQChartStyle.GetStyleConfig(HQChart.STYLE_TYPE_ID.BLACK_ID);

				blackStyle.BGColor = 'rgb(12,23,37)'; //背景
				blackStyle.FrameTitleBGColor = 'rgb(16,28,45)'; //指标标题背景
				blackStyle.FrameSplitTextColor = 'rgb(101,117,138)'; //刻度颜色

				//K线颜色
				blackStyle.UpBarColor = 'rgb(37,175,142)'; //K线上涨柱子颜色
				blackStyle.UpTextColor = blackStyle.UpBarColor; //上涨价格颜色
				blackStyle.DownBarColor = 'rgb(210,73,99)'; //K线下跌柱子颜色
				blackStyle.DownTextColor = blackStyle.DownBarColor; //下跌价格颜色

				//指标线段颜色
				blackStyle.Index.LineColor[0] = 'rgb(88,106,126)';
				blackStyle.Index.LineColor[1] = 'rgb(222,217,167)';
				blackStyle.Index.LineColor[2] = 'rgb(113,161,164)';

				//最新价格刻度颜色
				blackStyle.FrameLatestPrice.UpBarColor = 'rgb(37,175,142)';
				blackStyle.FrameLatestPrice.DownBarColor = 'rgb(210,73,99)';

				//面积图颜色
				blackStyle.CloseLineColor = 'rgb(113,121,133)'; //收盘价线颜色
				blackStyle.CloseLineAreaColor = ['rgba(36,41,57,0.8)', 'rgba(22,34,53,0.3)']; //收盘价面积图颜色

				//最高最低价颜色
				blackStyle.KLine.MaxMin.Color = 'rgb(255,250,240)';

				this.$refs.kline.style.backgroundColor = blackStyle.BGColor;
				HQChart.JSChart.SetStyle(blackStyle);

				this.KLine.Option.Symbol = this.Symbol;
				let chart = HQChart.JSChart.Init(this.$refs.kline);
				this.KLine.Option.NetworkFilter = this.NetworkFilter;
				chart.SetOption(this.KLine.Option);
				g_KLine.JSChart = chart;
			},

			CreateKLineChart_app() {
				if (g_KLine.JSChart) return;

				let element = new JSCommon.JSCanvasElement();
				// #ifdef APP-PLUS
				element.IsUniApp = true; //canvas需要指定下 是uniapp的app
				// #endif
				element.ID = 'kline2';
				element.Height = this.ChartHeight; //高度宽度需要手动绑定!!
				element.Width = this.ChartWidth;

				//var blackStyle=JSCommonHQStyle.GetStyleConfig(JSCommonHQStyle.STYLE_TYPE_ID.BLACK_ID);
				//JSCommon.JSChart.SetStyle(blackStyle);

				g_KLine.JSChart = JSCommon.JSChart.Init(element);
				this.KLine.Option.NetworkFilter = (data, callback) => {
					this.NetworkFilter(data, callback);
				};
				this.KLine.Option.Symbol = this.Symbol;
				this.KLine.Option.IsClickShowCorssCursor = true;
				this.KLine.Option.IsFullDraw = true; //每次手势移动全屏重绘
				g_KLine.JSChart.SetOption(this.KLine.Option);
			},

			CreateKLineChart() {
				// #ifdef H5
				this.CreateKLineChart_h5();
				// #endif

				// #ifndef H5
				this.CreateKLineChart_app();
				// #endif
			},

			NetworkFilter(data, callback) {
				// console.log('[KLineChart::NetworkFilter] data', data);
				switch (data.Name) {
					case 'KLineChartContainer::ReqeustHistoryMinuteData': //分钟全量数据下载
						this.RequestHistoryMinuteData(data, callback);
						break;
					case 'KLineChartContainer::RequestFlowCapitalData': //数字货币不会调用
						this.RequestFlowCapitalData(data, callback);
						break;
					case 'KLineChartContainer::RequestHistoryData': //日线全量数据下载
						this.RequestHistoryData(data, callback);
						break;
				}
			},

			//
			//WS
			//心跳包
			SendWSHeartMessage() {
				if (this.SocketOpen) {
					var pong = {
						'pong': new Date().getTime()
					};
					var message = JSON.stringify(pong);
					uni.sendSocketMessage({
						data: message
					});
				}
			},

			//取消订阅上一次的信息
			SendUnSubscribeMessage() {
				if (!this.LastSubString || !this.SocketOpen) return;

				var message = JSON.stringify({
					unsub: this.LastSubString
				}); //取消上次订阅的信息
				uni.sendSocketMessage({
					data: message
				});
				this.LastSubString = null; //清空最后一个订阅信息
			},

			RequestWSData(data, recvCallback) {
				if (!this.SocketOpen) {
					uni.connectSocket({
						url: this.WSUrl
					}); //创建连接

					uni.onSocketOpen((event) => {
						this.SocketOpen = true;
						// console.log(event);
						var message = JSON.stringify(data.SendData);
						uni.sendSocketMessage({
							data: message
						});
						if (data.SendData.sub) this.LastSubString = data.SendData.sub;
					});
				} else {
					this.SendUnSubscribeMessage();
					var message = JSON.stringify(data.SendData);
					uni.sendSocketMessage({
						data: message
					});
					if (data.SendData.sub) this.LastSubString = data.SendData.sub; //保存最后一个订阅信息
				}

				uni.onSocketMessage((event) => {
					let ploydata = new Uint8Array(event.data);
					let msg = pako.inflate(ploydata, {
						to: 'string'
					});
					//console.log("[KLineChart::RequestWSData] recv ", msg);
					var recvData = JSON.parse(msg);
					if (recvData.ping) {
						this.SendWSHeartMessage(); //回复服务器心跳包
					} else if (recvData.unsubbed) //取消订阅成功
					{

					} else if (recvData.subbed) //订阅成功 
					{

					} else {
						recvCallback(recvData, data);
					}
				});

				uni.onSocketError((evnet) => {
					// console.log(event);
				});

			},

			//生成请求数据
			GeneratePostData(symbol, period) {
				//1min, 5min, 15min, 30min, 60min,4hour,1day,1week, 1mon
				var MAP_PERIOD = new Map([
					[4, '1min'],
					[5, '5min'],
					[6, "15min"],
					[7, "30min"],
					[0, '1day'],
					[1, '1week'],
					[2, '1mon'],
					[3, '1year'],
				]);

				var strPeriod = MAP_PERIOD.get(period);

				var reqData = {
					req: `market.${symbol}.kline.${strPeriod}`,
					symbol: symbol,
					period: strPeriod
				};

				var subData = {
					sub: `market.${symbol}.kline.${strPeriod}`,
					symbol: symbol,
					period: strPeriod
				};

				return {
					Req: reqData,
					Sub: subData
				};
			},

			//请求分钟历史数据
			RequestHistoryMinuteData(data, callback) {
				data.PreventDefault = true;
				var symbol = data.Request.Data.symbol;
				var period = data.Self.Period; //周期

				var postData = this.GeneratePostData(this.OriginalSymbol, period);

				var obj = {
					SendData: postData.Req,
					Symbol: symbol,
					OriginalSymbol: this.OriginalSymbol,
					Period: period,
					Callback: callback
				};

				this.RequestWSData(obj, (recvData, data) => {
					this.RecvHistoryMinuteData(recvData, data);
				});
			},

			//接收历史分钟数据
			RecvHistoryMinuteData(recvData, data) {
				if (recvData.rep != data.SendData.req) return;

				var hqChartData = {
					code: 0,
					data: []
				};
				hqChartData.symbol = data.Symbol;
				hqChartData.name = data.OriginalSymbol;

				if (recvData.data) {
					var yClose = null; //前收盘
					for (var i in recvData.data) {
						var item = recvData.data[i];

						//时间戳转换
						var dateTime = new Date();
						dateTime.setTime(item.id * 1000);
						var date = dateTime.getFullYear() * 10000 + (dateTime.getMonth() + 1) * 100 + dateTime.getDate();
						var time = dateTime.getHours() * 100 + dateTime.getMinutes();

						var newItem = [date, yClose, item.open, item.high, item.low, item.close, item.vol, item.amount,
							time
						];

						yClose = item.close;
						hqChartData.data.push(newItem);
					}
				}
				// #ifdef H5
				data.Callback(hqChartData);
				// #endif

				// #ifndef H5
				data.Callback({
					data: hqChartData
				});
				// #endif

				this.SubscribeMinuteRealtimeData(data);
			},

			//订阅最新分钟K线数据
			SubscribeMinuteRealtimeData(data) {
				//订阅最新数据
				var postData = this.GeneratePostData(data.OriginalSymbol, data.Period);
				var obj = {
					SendData: postData.Sub,
					Symbol: data.Symbol,
					OriginalSymbol: data.OriginalSymbol,
					Period: data.Period
				};

				this.RequestWSData(obj, (recvData, data) => {
					this.RecvMinuteRealtimeData(recvData, data);
				});
			},

			RecvMinuteRealtimeData(recvData, data) {
				if (recvData.ch != data.SendData.sub) return;

				var internalChart = g_KLine.JSChart.JSChartContainer;
				var period = internalChart.Period;
				var symbol = internalChart.Symbol;
				if (symbol != data.Symbol || period != data.Period) return;

				var hqChartData = {
					code: 0,
					data: [],
					ver: 2.0
				}; //更新数据使用2.0版本格式
				hqChartData.symbol = data.Symbol;
				hqChartData.name = data.OriginalSymbol;

				//TODO:把recvData => hqchart内部格式 格式看教程
				//HQChart使用教程30-K线图如何对接第3方数据15-轮询增量更新1分钟K线数据

				var item = recvData.tick;

				var dateTime = new Date();
				dateTime.setTime(item.id * 1000);
				var date = dateTime.getFullYear() * 10000 + (dateTime.getMonth() + 1) * 100 + dateTime.getDate();
				var time = dateTime.getHours() * 100 + dateTime.getMinutes();
				var newItem = [date, null, item.open, item.high, item.low, item.close, item.vol, item.amount, time];
				this.last_price = item.close;
				this.lever_hight = item.high;
				this.lever_low = item.low;
				// this. change = (item.close - item.open) / item.open
				hqChartData.data.push(newItem);

				// #ifdef H5
				internalChart.RecvMinuteRealtimeData(hqChartData);
				// #endif

				// #ifndef H5
				internalChart.RecvMinuteRealtimeData({
					data: hqChartData
				});
				// #endif
			},


			//日K数据下载
			RequestHistoryData(data, callback) {
				data.PreventDefault = true;
				var symbol = data.Request.Data.symbol;
				var period = data.Self.Period; //周期
				var postData = this.GeneratePostData(this.OriginalSymbol, period);

				var obj = {
					SendData: postData.Req,
					Symbol: symbol,
					OriginalSymbol: this.OriginalSymbol,
					Period: period,
					Callback: callback
				};

				this.RequestWSData(obj, (recvData, data) => {
					this.RecvHistoryData(recvData, data);
				});
			},

			RecvHistoryData(recvData, data) //接收到日线数据 转化成hqchart格式数据
			{
				if (recvData.rep != data.SendData.req) return;

				var hqChartData = {
					code: 0,
					data: []
				};
				hqChartData.symbol = data.Symbol;
				hqChartData.name = data.OriginalSymbol;

				if (recvData.data) {
					var yClose = null; //前收盘
					for (var i in recvData.data) {
						var item = recvData.data[i];

						//时间戳转换
						var dateTime = new Date();
						dateTime.setTime(item.id * 1000);
						var date = dateTime.getFullYear() * 10000 + (dateTime.getMonth() + 1) * 100 + dateTime.getDate();
						var time = dateTime.getHours() * 100 + dateTime.getMinutes();

						var newItem = [date, yClose, item.open, item.high, item.low, item.close, item.vol, item.amount];
						this.last_price = item.close;
						this.lever_hight = item.high;
						this.lever_low = item.low;
						yClose = item.close;
						hqChartData.data.push(newItem);
					}
				}

				// #ifdef H5
				data.Callback(hqChartData);
				// #endif

				// #ifndef H5
				data.Callback({
					data: hqChartData
				});
				// #endif

				this.SubscribRealtimeData(data);
			},

			//订阅最新日K线数据
			SubscribRealtimeData(data) {
				//订阅最新数据
				var postData = this.GeneratePostData(data.OriginalSymbol, data.Period);

				var obj = {
					SendData: postData.Sub,
					Symbol: data.Symbol,
					OriginalSymbol: data.OriginalSymbol,
					Period: data.Period
				};

				this.RequestWSData(obj, (recvData, data) => {
					this.RecvRealtimeData(recvData, data);
				});
			},

			RecvRealtimeData(recvData, data) {
				if (recvData.ch != data.SendData.sub) return;

				var internalChart = g_KLine.JSChart.JSChartContainer;
				var period = internalChart.Period;
				var symbol = internalChart.Symbol;
				if (symbol != data.Symbol || period != data.Period) return;

				var hqChartData = {
					code: 0,
					stock: []
				};
				//TODO:把recvData => hqchart内部格式 格式看教程
				//HQChart使用教程30-K线图如何对接第3方数据14-轮询增量更新日K数据

				var stock = {
					symbol: data.Symbol,
					name: data.OriginalSymbol
				};
				var item = recvData.tick;
				var dateTime = new Date();
				dateTime.setTime(item.id * 1000);
				var date = dateTime.getFullYear() * 10000 + (dateTime.getMonth() + 1) * 100 + dateTime.getDate();
				var time = dateTime.getHours() * 100 + dateTime.getMinutes();
				this.last_price = item.close;
				stock.date = date;
				stock.yclose = null;
				stock.open = item.open;
				stock.high = item.high;
				stock.low = item.low;
				stock.price = item.close;
				stock.vol = item.vol;
				stock.amount = item.amount;

				hqChartData.stock.push(stock);

				// #ifdef H5
				internalChart.RecvRealtimeData(hqChartData);
				// #endif

				// #ifndef H5
				internalChart.RecvRealtimeData({
					data: hqChartData
				});
				// #endif
			},


			///
			//手势事件 app/小程序才有
			//KLine事件
			KLineTouchStart: function(event) {
				if (g_KLine.JSChart) g_KLine.JSChart.OnTouchStart(event);
			},

			KLineTouchMove: function(event) {
				if (g_KLine.JSChart) g_KLine.JSChart.OnTouchMove(event);
			},

			KLineTouchEnd: function(event) {
				if (g_KLine.JSChart) g_KLine.JSChart.OnTouchEnd(event);
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import './index.scss'
</style>
